﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SharingCenter.Web.User.Events
{
    using SharingCenter.Web.Classes;
    using SharingCenter.Web.Classes.enums;
    using SharingCenter.Web.Classes.Events;
    using SharingCenter.Web.Classes.Requests;

    public partial class MyEvents : EventPageBase
    {
        List<Sc_Event> eventList = new List<Sc_Event>();
        protected static bool showingPending = true;
        protected Guid currentShowingEventId;
        static List<Sc_SharedRequest> requestList = new List<Sc_SharedRequest>();

        protected void Page_Init(object sender, EventArgs e)
        {
            using (scDataContext cxt = new scDataContext())
            {
                var q = from entry in cxt.Sc_Events
                        where entry.CreatorUserId == Profile.UserId
                        orderby entry.StartDate ascending
                        select entry;
                eventList = q.ToList();
            }
            
            //btnRLOK.Click += new EventHandler(btnRLOK_Click);

            LinqDataSource1.Selecting += new EventHandler<LinqDataSourceSelectEventArgs>(LinqDataSource1_Selecting);
            //LinqDataSource1.Selected += new EventHandler<LinqDataSourceStatusEventArgs>(LinqDataSource1_Selected);
            LinqDataSource2.Selecting += new EventHandler<LinqDataSourceSelectEventArgs>(LinqDataSource2_Selecting);
            //ListView1.ItemDataBound += new EventHandler<ListViewItemEventArgs>(ListView1_ItemDataBound);
        }

        void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            ListViewDataItem item = (ListViewDataItem)e.Item;
            
            //Panel pnCancel = e.Item.FindControl
        }

        void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
        {
            
        }

        void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            //e.WhereParameters["StartDate"] = DateTime.Now;
            scDataContext cxt = new scDataContext();
                e.Result = from t in cxt.EventsWithPendingCounts
                           where t.CreatorUserId == Profile.UserId
                           && DateTime.Now < t.StartDate
                           select t;
            
        }

        void LinqDataSource2_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            e.WhereParameters["EndDate"] = DateTime.Now;
        }

        protected void btnRLOK_Command(object sender, CommandEventArgs e)
        {
            scDataContext.Instance.Dispose();
            
            if (showingPending)
            {
                Guid eventId = new Guid(hdnEventId.Value);
                //Sc_Event evt = EventOperations.GetEventFromEvnetId(eventId);
                List<Guid> userList = new List<Guid>();
                for (int i = 0; i < lvReqeusts.Items.Count; i++)
                {
                    Guid requestId = (Guid)lvReqeusts.DataKeys[i].Value;
                    int selectedIndex = ((RadioButtonList)lvReqeusts.Items[0].FindControl("rdoApprove")).SelectedIndex;
                    if (selectedIndex != 2)
                    {
                        RequestStatus ts = selectedIndex == 0 ? RequestStatus.Approved : RequestStatus.Rejected;
                        RequestOperations.ChangeRequestStatus(requestId, ts);
                        if (ts == RequestStatus.Approved)
                        {
                            userList.Add(new Guid(((HiddenField)lvReqeusts.Items[0].FindControl("hdnRequestorUserId")).Value));
                            //EventOperations.AddParticipantToEvent(eventId, uid, "", false);
                        }
                    }
                }

                //scDataContext.Instance.SubmitChanges();

                try
                {
                    //scDataContext.Instance.SubmitChanges();
                    EventOperations.AddParticipantsToEvent(eventId, userList, "");
                    this.SetTopMostMessage("操作已完成。", true);
                }
                catch
                {
                    this.SetTopMostMessage("服务器错误，请稍后重试。", true);
                }
                RefreshPage();
            }

            scDataContext.Instance.Dispose();
        }

        void btnRLOK_Click(object sender, EventArgs e)
        {
            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            
            //BindEventList();
            //BindPassedEventList();
            //BindUpdatePanelTrigers();
        }

        void BindUpdatePanelTrigers()
        {
            foreach (ListViewDataItem item in ListView1.Items)
            {
                //LinkButton tmp = (LinkButton)item.FindControl("btnShowPending");
                AjaxScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(item.FindControl("btnShowPending"));
                AjaxScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(item.FindControl("btnShowApproved"));
                /*
                AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
                trigger.ControlID = tmp.ID;
                trigger.EventName = "Command";
                upRequestList.Triggers.Add(trigger);*/
            }
        }

        //protected void BindEventList()
        //{
        //    //dataContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, dataContext.Sc_Events);
        //    using (scDataContext cxt = new scDataContext())
        //    {
        //        var q = from e in cxt.Sc_Events
        //                where e.CreatorUserId == Profile.UserId && DateTime.Now < e.StartDate
        //                select new
        //        {
        //            EventId = e.EventId,
        //            Entry = e,
        //            PendingCount = Classes.Requests.RequestOperations.GetRequestsByEntityType(EntityType.UserEvent, e.EventId
        //            , RequestStatus.Pending, LogicalOperator.Is).Count
        //        };

        //        //dataContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues);
        //        ListView1.DataSource = q;
        //        ListView1.DataBind();
        //    }
        //}

        //protected void BindPassedEventList()
        //{
        //    var q = from entry in eventList
        //            where DateTime.Now > entry.EndDate
        //            select entry;

        //    ListView2.DataSource = q;
        //    ListView2.DataBind();
        //}

        
        protected void EventAction(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "DeleteEvent":
                    Classes.Events.EventOperations.DeleteEvent(new Guid(e.CommandArgument.ToString()));
                    this.SetTopMostMessage("已删除一条活动信息。", true);
                    RefreshPage(true);
                    break;
                default: break;
            }
        }

        protected void ShowRequestList(object sender, CommandEventArgs e)
        {
            Guid eventIdToShow = new Guid(e.CommandArgument.ToString());
            //string a = ListView1.DataKeyNames;
            switch (e.CommandName)
            {
                case "Approved":
                    ltrListTitle.Text = "已确认成员";
                    RequestList(RequestStatus.Approved, eventIdToShow);
                    MultiView1.ActiveViewIndex = 1;
                    break;
                case "Pending":
                    ltrListTitle.Text = "待确认成员";
                    RequestList(RequestStatus.Pending, eventIdToShow);
                    MultiView1.ActiveViewIndex = 0;
                    break;
                default: break;
            }
        }

        void RequestList(RequestStatus status, Guid eventId)
        {
            showingPending = status == RequestStatus.Pending;
            Sc_Event evt = EventOperations.GetEventFromEvnetId(eventId);
            hdnEventId.Value = eventId.ToString();
            hdnEventName.Value = evt.Title;

            //List<Sc_SharedRequest> reqList = RequestOperations.GetRequestsByEntityType(EntityType.UserEvent, eventId, RequestStatus.Pending, LogicalOperator.Is);
            if (showingPending)
            {
                requestList = RequestOperations.GetRequestsByEntityType(EntityType.UserEvent, eventId, RequestStatus.Pending, LogicalOperator.Is);
                lvReqeusts.DataSource = requestList;
                lvReqeusts.DataBind();
                //btnRLOK.CommandArgument = currentShowingEventId.ToString();
            }
            else
            {
                var q = from t in EventOperations.GetParticipantsByEventId(EntityType.UserEvent, eventId)
                        select new { UserId = t };
                lvApproved.DataSource = q;
                lvApproved.DataBind();
            }
            
            upRequestList.Update();
        }

        protected void RegAsyncPostBack(object sender, EventArgs e)
        {
            AjaxScriptManager.GetCurrent(this).RegisterAsyncPostBackControl((Control)sender);
        }

    }
}
